import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { login, register } from '@/api/login';
import { CODE } from '@/api/constants';
import { result } from '@/utils/result';
import { UnauthenticatedError } from '@/api/request';

const useTokenStore = defineStore('auth-token', () => {
    const token = ref("")
    const isLogin = computed(()=>{
        return token.value.length > 0
    })

    // 返回令牌请求头
    const getAuthHeader = () => {
        if (!isLogin.value) throw new UnauthenticatedError()
        return {
            Authorization: `Bearer ${token.value}`
        }
    }

    // 用户注册，注册成功后自动登录，并登记token
    const registerUser = async (nickname, email, password) => {
        const resp = await register({nickname, email, password})
        if (resp.code != CODE.OK) {
            return result(false, resp.msg)
        }
        token.value = resp.data.accessToken
        return result(true, "注册成功")
    }

    // 用户登录，并登记token
    const loginUser = async (nickname, password) => {
        const resp = await login({nickname, password})
        if (resp.code != CODE.OK) {
            return result(false, resp.msg)
        }
        token.value = resp.data.accessToken
        return result(true, "登录成功")
    }

    // 用户登出，清楚缓存的token
    const logoutUser = () => {
        token.value = ""
    }
    return { token, isLogin, getAuthHeader, registerUser, loginUser, logoutUser }
}, {
    persist: {
        paths: ['token'],
        serializer: {
            serialize: JSON.stringify,
            deserialize: JSON.parse
        }
    }
})

export default useTokenStore;